package com.hhxy.service;

import com.hhxy.mapper.UserMapper;
import com.hhxy.pojo.User;
import com.hhxy.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost方法被调用了。。。");
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet方法被调用了。。。");
        //1、接收请求数据，接收用户输入的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //2、使用MyBatis完成查询
        //2.1 获取SqlSessionFactory对象
        SqlSessionFactory sqlSF = SqlSessionFactoryUtils.sqlSF();
        //2.2 获取SqlSession对象
        SqlSession sqlS = sqlSF.openSession();
        //2.3 获取Mapper接口对象
        UserMapper userMapper = sqlS.getMapper(UserMapper.class);
        /*----------------------核心代码（其他的可以CV）----------------------------*/
        //2.4 执行SQL语句
        User user = userMapper.select(username, password);
        /*-------------------------------------------------------------------------*/
        //2.5 释放资源
        sqlS.close();

        //3、处理结果，发送响应数据
        //3.1 设置响应数据格式
        response.setContentType("text/html;charset=utf-8");
        //3.2 获取响应数据输出流，用于响应数据
        PrintWriter pw = response.getWriter();
        //3.2 判断user对象是否为空，确定账号是否存在
        if(user == null){
            pw.write("登陆失败，请重新登录！");
        }else{
            pw.write("登陆成功！");
        }
        pw.write("你好丫");
    }
}
